package com.bilibili.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.bilibili.domain.exception.ConditionException;

import java.util.Calendar;
import java.util.Date;


/**
 * projectName:com.bilibili.utils
 *
 * @author 飞
 * @create by 2024/6/310:31
 * description:
 */
public class TokenUtil {

    private static final String ISSUER = "签发者";
    public static String generateToken(Long userId) throws Exception{
        Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(),RSAUtil.getPrivateKey());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE,30);//有效期
        return JWT.create()//创建jwt令牌
                .withKeyId(String.valueOf(userId))
                .withIssuer(ISSUER)//签发者
                .withExpiresAt(calendar.getTime())//标识过期时间
                .sign(algorithm);
    }

    public static Long verifyToken(String token)//验证
    {

        try {//不能使用抛异常的方式
            Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(),RSAUtil.getPrivateKey());
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            String userId = jwt.getKeyId();
            return Long.valueOf(userId);
        } catch (TokenExpiredException e) {
            throw new ConditionException("555","token过期！");
        }catch (Exception e){
            throw new ConditionException("非法用户token！");
        }
    }

    public static String generateRefreshToken(Long userId) throws Exception {
        Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(),RSAUtil.getPrivateKey());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH,7);//有效期
        return JWT.create()//创建jwt令牌
                .withKeyId(String.valueOf(userId))
                .withIssuer(ISSUER)//签发者
                .withExpiresAt(calendar.getTime())//标识过期时间
                .sign(algorithm);
    }
}
